package day14;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;

//服务端
public class Server2 {
    //保存进入了聊天室的客户端对象
    static List<Socket> list = new ArrayList<>();
    public static void main(String[] args) throws IOException {
        ServerSocket server = new ServerSocket(9999);
        while (true){
            Socket client = server.accept();
            list.add(client);//类似于加入群聊
            System.out.println("聊天室："+list.size()+"人");
            //创建线程：负责多次客户端读取,负责给其他所有客户端再写入
            new ServerThread2(client).start();
        }
    }
}
class ServerThread2 extends Thread{
    Socket client;
    public ServerThread2(Socket client){
        this.client = client;
    }
    public void run() {
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(client.getInputStream()));
            while (true){
                //读取当前客户端数据
                String msg = br.readLine();
                if (msg!=null){
                    //向其他客户端写入
                    System.out.println(client.getInetAddress()+":"+msg);
                    //如果客户端写入的数据包含了esc 表示想退出
                    if (msg.contains("esc")){
                        //退出聊天室的功能
                        int index = msg.indexOf(":");
                        String name = msg.substring(0,index);
                        Server2.list.remove(client);
                        System.out.println(name+"已退出,聊天室的人数:"+Server2.list.size());
                        break;
                    }
                    for (Socket s:Server2.list){
                        if (s!=client){
                            //如果有的客户端没有正常关闭,再写入数据就会出现异常
                            //导致后面的循环不会执行 所有需要try-catch
                            try {
                                s.getOutputStream().write((msg+"\n").getBytes());
                            }catch (Exception e){

                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            //报错就是异常关闭
        }

    }
}